package com.le.admin.current.api.mytools;

import com.le.common.utils.FileUtils;
import com.le.common.utils.PdfUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/tools/pdf")
public class PdfToolController {

    /**
     * pdf文件切割成图片输出
     * @param pdfFile
     * @return
     */
    @PostMapping("/pdfCutToImage")
    public ResponseEntity<byte[]> processPdf(@RequestParam("pdfFile") MultipartFile pdfFile) {
        try {
            File tempDir = FileUtils.createTempDirectory();
            File pdfInputFile = new File(tempDir, pdfFile.getOriginalFilename());
            pdfFile.transferTo(pdfInputFile);

            // 将PDF文件拆分为单独的图像
            PdfUtils.splitPdfToImages(pdfInputFile, tempDir);

            // 将图像压缩为zip文件
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            FileUtils.zipImages(tempDir, baos);

            // 删除临时目录及其内容
            FileUtils.deleteDirectory(tempDir);

            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attachment; filename=images.zip");

            return ResponseEntity.ok()
                    .headers(headers)
                    .contentType(MediaType.parseMediaType("application/zip"))
                    .body(baos.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }



}
